package com.bamboo.tool.util;

import cn.hutool.core.collection.CollUtil;
import com.bamboo.tool.entity.JavaFieldInfo;
import com.bamboo.tool.enums.DataType;

import java.util.*;

/**
 * @author bamboo
 * Date 2022/10/19 12:22
 * Description
 */
public class JavaFieldInfoUtil {

    public static Object toJson(JavaFieldInfo javaFieldInfo) {
        DataType arrayType = javaFieldInfo.getArrayType();
        DataType fieldType = javaFieldInfo.getFieldType();
        Object defaultValue = fieldType.getDefaultValue();
        List<JavaFieldInfo> children = javaFieldInfo.getChildren();
        Object value = null;
        if (fieldType.equals(DataType.MAP)) {
            value = new HashMap<>();
        } else if (fieldType.equals(DataType.OBJECT)) {
            Map<Object, Object> objectMap = new HashMap<>();
            if (CollUtil.isNotEmpty(children)) {
                children.stream().forEach(e -> {
                    objectMap.put(e.getFieldName(), toJson(e));
                });
            }
            value = objectMap;
        } else if (fieldType.equals(DataType.FILE)) {
            value = "文件类型无法解析";
        } else {
            value = defaultValue;
        }
        if (arrayType != null) {
            value = Arrays.asList(value);
        }
        return value;
    }
}
